package com.gitee.cashzhang27.test.boot.other.config;

import javax.annotation.Resource;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties.Pool;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author Cash Zhang
 * @version v1.0
 * @since 2019/02/17 14:15
 */
@Configuration
public class MyRedisConfig {
/*
  @Bean("userRedisTemplate")
  public RedisTemplate<Object, User> userRedisTemplate(
      RedisConnectionFactory redisConnectionFactory) {
    Jackson2JsonRedisSerializer<User> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(
        User.class);
    RedisTemplate<Object, User> template = new RedisTemplate<>();
    template.setConnectionFactory(redisConnectionFactory);
    template.setDefaultSerializer(jackson2JsonRedisSerializer);
    return template;
  }
*/
  @Bean
  public RedisTemplate<Object, Object> redisTemplate(
      RedisConnectionFactory redisConnectionFactory) {
    GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
    RedisTemplate<Object, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(redisConnectionFactory);
    template.setDefaultSerializer(genericJackson2JsonRedisSerializer);
    return template;
  }


  @Resource
  private RedisProperties redisProperties;

  @Bean
  public JedisPool jedisPool() {
    Pool pool = redisProperties.getJedis().getPool();
    JedisPoolConfig config = new JedisPoolConfig();
    config.setMaxTotal(pool.getMaxActive());
    config.setMaxIdle(pool.getMaxIdle());
    config.setMinIdle(pool.getMinIdle());
    if (pool.getMaxWait() != null) {
      config.setMaxWaitMillis(pool.getMaxWait().toMillis());
    }
    if (StringUtils.isEmpty(redisProperties.getPassword())) {
      return new JedisPool(config, redisProperties.getHost(), redisProperties.getPort(),
          redisProperties.getTimeout().getNano());
    }
    return new JedisPool(config, redisProperties.getHost(), redisProperties.getPort(),
        redisProperties.getTimeout().getNano(), redisProperties.getPassword(),
        redisProperties.getDatabase());
  }
}
